package com.scs.application.modules.upms.wxmp.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.entity.WxmpMember;
import com.scs.application.modules.upms.service.UserService;
import com.scs.application.modules.upms.service.WxmpMemberService;
import com.scs.application.modules.upms.wxmp.builder.TextBuilder;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 */
@AllArgsConstructor
@Component
public class SubscribeHandler extends AbstractHandler {

    public static final String ACTION_BIND_USER = "bind_user";

    private final WxmpMemberService wxmpMemberService;

    private final UserService userService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser());


        // 获取微信用户基本信息
        String userId = null;
        try {
            WxMpUser userWxInfo = weixinService.getUserService()
                    .userInfo(wxMessage.getFromUser(), null);
            // 场景值 存储的是 {\"action\":\"user_bind\",\"userId\":\"1\"}
//            String qrSceneStr = userWxInfo.getQrSceneStr();
            String qrSceneStr = WxConsts.EventType.SUBSCRIBE.equals(wxMessage.getEvent()) ? userWxInfo.getQrSceneStr() : wxMessage.getEventKey();

            if (StringUtils.isBlank(qrSceneStr)) {
                return null;
            }

            try {
                JSONObject jsonObject = JSON.parseObject(qrSceneStr);
                if (!ACTION_BIND_USER.equalsIgnoreCase(jsonObject.getString("action"))) {
                    logger.info("当前非绑定账号场景");
                    return new TextBuilder().build("感谢关注，您还未绑定账号，绑定后才能进行消息通知哦！", wxMessage, weixinService);
                }
                userId = jsonObject.getString("userId");

            } catch (Exception e) {
                logger.error("场景字符串错误");
                return null;
            }


            String appId = weixinService.getWxMpConfigStorage().getAppId();
            /*int count = wxmpMemberService.count(Wrappers.<WxmpMember>query().eq("app_id", appId).eq("open_id", userWxInfo.getOpenId()));
            if (count != 0) {
                return new TextBuilder().build("感谢关注，您已经绑定过账号了", wxMessage, weixinService);
            }*/
            /*count = wxmpMemberService.count(Wrappers.<WxmpMember>query().eq("app_id", appId).eq("user_id", userId));
            if (count != 0) {
                return new TextBuilder().build("感谢关注，该账号已经绑定过其他微信账号了。如非本人账号，请去XX界面进行解绑", wxMessage, weixinService);
            }*/

            User user = userService.getById(userId);

            if (userWxInfo != null && user != null) {
                int count = wxmpMemberService.count(Wrappers.<WxmpMember>query().eq("app_id", appId).eq("open_id", userWxInfo.getOpenId()).eq("user_id", user.getId()));
                if (count != 0) {
                    return new TextBuilder().build("感谢关注，您已经绑定过该账号了", wxMessage, weixinService);
                }

                WxmpMember member = new WxmpMember();
                member.setAppId(appId).setOpenId(userWxInfo.getOpenId())
                        .setUserId(userId)
                        .setLoginKey(user.getLoginKey())
                        .setNickname(userWxInfo.getNickname())
                        .setSexDesc(userWxInfo.getSexDesc())
                        .setHeadImgUrl(userWxInfo.getHeadImgUrl())
                        .setGmtJoined(new Date());
                wxmpMemberService.saveCascadeById(member);
                return new TextBuilder().build(String.format("感谢关注，您已成功绑定账号%s(%s)", user.getLoginKey(), user.getNickname()), wxMessage, weixinService);
            }
        } catch (WxErrorException e) {
            if (e.getError().getErrorCode() == 48001) {
                this.logger.info("该公众号没有获取用户信息权限！");
            }
        }

        return null;
    }

    /**
     * 处理特殊请求，比如如果是扫码进来的，可以做相应处理
     */
    private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage)
            throws Exception {
        return null;
    }

}
